//
//  CHJUploadManager.m
//  
//
//  Created by jiaxuzhou on 2017/12/2.
//

#import "CHJUploadManager.h"
#import "CHJUploadTask.h"
#import "CHJUploadVideo.h"

NSString * const kUploadNotificationStartUpload     = @"kUploadNotificationStartUpload";
NSString * const kUploadNotificationProgress        = @"kUploadNotificationProgress";
NSString * const kUploadNotificationSpeed           = @"kUploadNotificationSpeed";
NSString * const kUploadNotificationComplate        = @"kUploadNotificationComplate";
NSString * const kUploadNotificationFaild           = @"kUploadNotificationFaild";


@implementation CHJUploadManager

+ (CHJUploadManager *)sharedInstance
{
    static CHJUploadManager *uploadShared = nil;
    if (!uploadShared) {
        @synchronized(self) {
            if (!uploadShared) uploadShared = [[self alloc] init];
        }
    }
    return uploadShared;
}

- (id)init {
    self = [super init];
    if (self) {
        [self initDownloadQueue];
        [self initDownloadDB];
        return self;
    }
    return nil;
}

- (void)initDownloadQueue {
    queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
    [queue addObserver:self forKeyPath:@"operationCount" options:NSKeyValueObservingOptionNew context:nil];
}


- (void)initDownloadDB
{
    uploadModel = [CHJUploadModel sharedInstance];
}

- (void)uploadComplateWithVideo:(CHJUploadVideo *)video
{
    [uploadModel updateVideo:video];
    //    if ( video != nil) {
    NSDictionary *info = @{@"video":video};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kUploadNotificationComplate object:info userInfo:info];
    //    }
}

//添加新任务
- (BOOL)addUploadVideo:(CHJUploadVideo *)video
{
    if ([uploadModel refreshVideo:video] == nil) {
        [uploadModel addVideo:video];
    }
    else
    {
        [uploadModel updateVideo:video];
    }
    
    [self uploadStartUploadWithVideo:video];
    
    __block int faildCount = 0;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSOperation *task = [self switchTask:video];
        if (task) {
            [queue addOperation:task];
        }
    });
    
    return YES;
}

- (void)delLocalVideo:(CHJUploadVideo *)video
{
    NSArray *tasks = [queue operations];
    for (CHJUploadTask *task in tasks) {
        if ([task.video.filePath isEqualToString:video.filePath]) {
            [task cancel];
            break;
        }
    }
    
    [self removeLocalVideoFile:video isKeepThumb:NO];
    [uploadModel delVideo:video];
}

- (void)listVideo:(NSString *)where withBlock:(CHJUploadModelBlock)block
{
    [uploadModel listVideo:where withBlock:block];
}

- (void)getUploadUnfinish:(CHJUploadModelBlock)block
{
    NSString *where = [NSString stringWithFormat:@"isFinish < 1 AND uploadStatus < 3 AND suid='%@' AND status!=0",self.suid];
    [uploadModel listVideo:where withBlock:block];
}

- (void)getUploadFailed:(CHJUploadModelBlock)handler
{
    NSString *where = [NSString stringWithFormat:@"isFinish < 1 AND uploadStatus = 3  AND suid='%@'",self.suid];
    
    [uploadModel listVideo:where withBlock:handler];
}

- (void)resumeOperationFailedVideo:(CHJUploadVideo *)video
{
    [self addUploadVideo:video];
}

//选择上传任务
- (NSOperation *)switchTask:(CHJUploadVideo *)video {
    NSOperation *task = nil;

        task = [[CHJUploadTask alloc] initWithVideo:video];
        ((CHJUploadTask *) task).uploadManager = self;
    return task;
}

- (void)updateSpeed:(CGFloat)speed withVideo:(CHJUploadVideo *)video {
    NSDictionary *info = @{@"video":video,@"speed":@(speed)};
    [[NSNotificationCenter defaultCenter] postNotificationName:kUploadNotificationSpeed object:info userInfo:info];
    
}

- (void)updateProgress:(CGFloat)progress withVideo:(CHJUploadVideo *)video {
    //        [uploadModel updateVideo:video];
    //    NSLog(@"%@",video.progress);
    NSDictionary *info = @{@"video":video,@"progress":@(progress)};
    [[NSNotificationCenter defaultCenter] postNotificationName:kUploadNotificationProgress object:info userInfo:info];
}

//消息
- (void)uploadStartUploadWithVideo:(CHJUploadVideo *)video
{
    video = [uploadModel refreshVideo:video];
    if ( video != nil) {
        NSDictionary *info = @{@"video":video};
        [[NSNotificationCenter defaultCenter] postNotificationName:kUploadNotificationStartUpload object:info userInfo:info];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kUploadNotificationStartUpload object:nil userInfo:nil];
        
    }
}

- (void)removeLocalVideoFile:(CHJUploadVideo *)video isKeepThumb:(BOOL)isKeep {
    NSError *error;
    NSFileManager *fm = [NSFileManager defaultManager];
    if (video.filePath) {
        [fm removeItemAtPath:video.filePath error:&error];
    }
}

@end
